<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div>
      <div class="btns">
        <button data-path="/news">新闻</button>
        <button data-path="/music">音乐</button>
        <button data-path="/play">娱乐</button>
      </div>
      <div id="content"></div>
    </div>

    <script>
      const routes = [
        { path: "/news", content: "我是新闻列表" },
        { path: "/play", content: "我是娱乐列表" },
        { path: "/music", content: "我是音乐列表" },
      ];

      const oContent = document.getElementById("content");
      const btns = document.querySelectorAll(".btns button");
      //给按钮绑定点击事件,修改路径的hash地址
      for (var i = 0; i < btns.length; i++) {
        btns[i].onclick = function () {
          //history对象提供了一个pushState的方法,可以无刷新的改变地址
          history.pushState(null, null, this.dataset.path);

          //点击完按钮之后,直接遍历routes 改变content内容
          routes.forEach((item) => {
            if (item.path === this.dataset.path) {
              oContent.textContent = item.content;
            }
          });
        };
      }

      //我们有一个监听历史记录改变的事件 popstate
      window.onpopstate = function () {
        // console.log(1);
        //当历史记录改变后,获取最新的地址 location.pathname
        // console.log(location.pathname);

        //点击完按钮之后,直接遍历routes 改变content内容
        routes.forEach((item) => {
          if (item.path === location.pathname) {
            oContent.textContent = item.content;
          }
        });
      };
    </script>
  </body>
</html>
